package com.example.homework;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class MyDAO {

    private SQLiteDatabase db;

    // 初始化数据库
    public MyDAO(Context context) {
        Myopenhelper myopenhelper = new Myopenhelper(context, "ctDB", null, 1);
        db = myopenhelper.getWritableDatabase();
    }

    // 重置数据表
    public void resetTable() {
        db.execSQL("DROP TABLE IF EXISTS person");
        db.execSQL("CREATE TABLE person (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)");
    }

    // 插入数据
    public void insert(String name, int age) {
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("age", age);
        db.insert("person", null, values);
    }

    public String queryAll() {
        Cursor cursor = db.query("person", null, null, null, null, null, null);
        StringBuilder result = new StringBuilder();
        // 遍历查询结果
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            int age = cursor.getInt(cursor.getColumnIndex("age"));
            result.append("ID: ").append(id).append(", 姓名: ").append(name).append(", 年龄: ").append(age).append("\n");
        }
        cursor.close();
        return result.toString();
    }

    // 这里通过姓名更新年龄
    public void update(String name, int newAge) {
        ContentValues values = new ContentValues();
        values.put("age", newAge);
        db.update("person", values, "name = ?", new String[]{name});
    }

    // 这里通过姓名删除数据
    public void delete(String name) {
        db.delete("person", "name = ?", new String[]{name});
    }
}
